# -*- encoding:utf-8 -*-
from __future__ import print_function

import sys
import random
from flask import ( Flask, jsonify, request )
from textrank4zh import TextRank4Keyword


try:
  reload(sys)
  sys.setdefaultencoding('utf-8')
except:
  pass


app = Flask(__name__)
@app.route('/wallpaper/generator/article/keywords',methods=['post'])
def getKeywords():
  argKeywordMinLen = request.json.get("keywordMinLen")
  argKeywordMaxLen = request.json.get("keywordMaxLen")
  text = request.json.get("text")

  tr4w = TextRank4Keyword()
  # py2中text必须是utf8编码的str或者unicode对象，py3中必须是utf8编码的bytes或者str对象
  tr4w.analyze(text=text, lower=True, window=2)

  templates = [
    [
      ['nh', 'nh'],
      [
        [1, ["的"]],  # 张三的李四
        [2, ["和"]],  # 张三和李四
        [2, ["与"]]   # 张三和李四
      ]
    ],
    [
      ['n', 'n'],
      [
        [2, ["和"]]  # 汽车和筷子
      ]
    ],
    [
      ['a', 'n'],
      [
        [1, ["的"]]   # 白色的门
      ]
    # ],
    # [
    #   ['n', 'v', 'n'] # 娘娘驾驶汽车
    # ],
    # [
    #   ['nh', 'v', 'n'] # 张三驾驶汽车
    ]
  ]

  adjList = [
    "善良的", "独立的",
    "莽撞的", "执著的",
    "谨慎的", "胆怯的",
    "温和的", "老实的",
    "平和的", "啰嗦的"
  ]

  def analyzeKeywords(count, minLen):
    keywords = tr4w.get_keywords(count, word_min_len=minLen)
    keywordList = []
    for item in keywords:
      # print(item.word, item.weight)
      keywordList.append(item.word)
    return keywordList


  def analyzeKeyphrases(count, minLen):
    keyphrases = tr4w.get_keyphrases(count, minLen)

    keyphrasesList = []
    for phrase in keyphrases:
      keyphrasesList.append(phrase)
    return keyphrasesList


  def analyzeSpeech(words):
    from ltp import LTP
    ltp = LTP("LTP/small")  # 默认加载 Small 模型
    # ltp = LTP("LTP/base2")  # 加载 base2 模型
    output = ltp.pipeline(words, tasks=["cws", "pos"])

    # 使用字典格式作为返回结果
    # print('-----高频词:')
    # print(output.cws)  # print(output[0]) / print(output['cws']) # 也可以使用下标访问
    # print('-----词性:')
    # print(output.pos)
    return [output.cws, output.pos]


  def generateKeywords(arg, minLen, maxLen):
    cws = arg[0]
    pos = arg[1]
    total = len(cws)

    res = {"init"}
    # 两个词组合
    for i in range(total):
      for j in range(total):
        if i != j:
          for combination in templates:
            if (len(combination[0]) < 3
              and pos[i][0] == combination[0][0]
              and pos[j][0] == combination[0][1]):
              for method in combination[1]:
                if method[0] == 1:
                  for pad in method[1]:
                    resTemp1 = cws[i][0] + pad + cws[j][0]
                    if len(resTemp1) >= minLen and len(resTemp1) <= maxLen:
                      res.add(resTemp1)
                if method[0] == 2:
                  for pad in method[1]:
                    resTemp2 = cws[i][0] + pad + cws[j][0]
                    resTemp3 = cws[i][0] + pad + cws[j][0]
                    if len(resTemp2) >= minLen and len(resTemp2) <= maxLen:
                      res.add(resTemp2)
                    if len(resTemp3) >= minLen and len(resTemp3) <= maxLen:
                      res.add(resTemp3)

    # 三个词组合
    for i in range(total):
      for j in range(total):
        for k in range(total):
          if (i != j) and (j != k) and (k != i):
            for combination in templates:
              if (len(combination[0]) == 3
                and pos[i][0] == combination[0][0]
                and pos[j][0] == combination[0][1]
                and pos[k][0] == combination[0][2]):

                resTemp4 = cws[i][0] + cws[j][0] + cws[k][0]
                if len(resTemp4) >= minLen and len(resTemp4) <= maxLen:
                  res.add(resTemp4)

    res.remove("init")
    return res


  def generateAdjNoun(arg, minLen, maxLen, limit=10):
    cws = arg[0]
    pos = arg[1]
    total = len(cws)
    res = {"init"}
    metNoneIndex = {-1}

    for j in range(total):
      if ((not (j in metNoneIndex))
        and (pos[j][0] == 'nh' or pos[j][0] == 'n')
        and len(res) < limit+1):
        randomSeed = random.randint(0,len(adjList)-1)

        resTemp = adjList[randomSeed] + cws[j][0]
        if len(resTemp) >= minLen and len(resTemp) <= maxLen:
          res.add(resTemp)
          metNoneIndex.add(j)

    res.remove("init")
    # metNoneIndex.remove(-1)
    # print('-----形容词组合:' + str(len(res)))
    # print(res)
    return res


  def main(wordCount, wordMinLen, kwMinLen, kwMaxLen, limit=50):
    mainRes = []

    # 词频词性分析
    keywordsRes = analyzeKeywords(wordCount, wordMinLen)
    kwWithSpeech = analyzeSpeech(keywordsRes)

    # 添加关键短语
    keyphase = analyzeKeyphrases(20, 2)
    # print('-----关键短语列表:')
    # print(keyphase)
    for i in range(len(keyphase)):
      if len(keyphase[i]) >= kwMinLen and len(keyphase[i]) <= kwMinLen:
        mainRes.append(keyphase[i])

    # 添加形容词随机组合
    adjNounRes = generateAdjNoun(kwWithSpeech, kwMinLen, kwMaxLen)
    adjNounResList = list(adjNounRes)
    mainRes = mainRes + adjNounResList

    # 添加组合关键词
    kwRes = generateKeywords(kwWithSpeech, kwMinLen, kwMaxLen)
    kwResList = list(kwRes)

    mainRes = mainRes + kwResList[:limit-len(mainRes)]
    return mainRes


  mainRes = main(20, 1, int(argKeywordMinLen), int(argKeywordMaxLen))
  # print('-----关键词:')
  # print(mainRes)
  # print('共计: ' + str(len(mainRes)))

  del argKeywordMinLen
  del argKeywordMaxLen
  del text
  del tr4w

  return jsonify({"keywords": mainRes})

if __name__ == '__main__':
  app.run(host="0.0.0.0", port=10030)
